package com.xiweicheng.test.springcloud.ms.a;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import lombok.extern.slf4j.Slf4j;

//@SpringBootApplication
//@EnableDiscoveryClient
//@EnableCircuitBreaker
@SpringCloudApplication
@EnableFeignClients
@RestController
@Slf4j
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @LoadBalanced
    @Bean
    RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Autowired
    Environment env;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient client;

    @Autowired
    Registration registration;

    @Autowired
    HelloService helloService;

    @GetMapping("hello")
    public String hello() {
        return "hello, i am service: " + env.getProperty("spring.application.name") + ", on port:"
                + env.getProperty("server.port") + ", service id: " + registration.getServiceId();
    }

    @GetMapping("ac")
    @HystrixCommand(fallbackMethod = "acFallback")
    public String ac(@RequestParam(value = "method", defaultValue = "hello") String method,
            @RequestParam(value = "sleep", defaultValue = "0") int sleep) {
        log.debug("service id: " + registration.getServiceId());
        return restTemplate.getForObject("http://ms-c/{1}?sleep={2}", String.class, method, sleep);
    }

    public String acFallback(String method, int sleep) {
        String val = "hystrix fallback for /ac!" + " method: " + method + " sleep: " + sleep;
        log.debug(val);
        return val;
    }

    @GetMapping("ac2")
    public String ac2(@RequestParam(value = "sleep", defaultValue = "0") int sleep) {
        String val = helloService.hello(sleep);
        log.debug(val);
        return val;
    }

    @GetMapping("ac3")
    public String ac3() {
        String val = helloService.none();
        log.debug(val);
        return val;
    }

}
